<template>
  <div class="main">
    <xr-header
      :label="logData.label">
      <el-tooltip
        slot="otherLabel"
        effect="dark"
        placement="top">
        <div slot="content" v-html="logData.labelDes" />
        <i class="wk wk-help wk-help-tips" />
      </el-tooltip>
    </xr-header>
    <div class="main-body">
      <flexbox class="main-table-header">
        <el-date-picker
          v-model="dateTime"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间" />
        <wk-user-dialog-select
          v-model="userList"
          :radio="false"
          collapse-tags
          placeholder="操作人" />
        <el-select
          v-model="apply"
          style="width: 160px;"
          placeholder="操作应用"
          clearable
          filterable
          :filter-method="(query)=> {filterMethod(query, 'applyList')}"
          @change="getModuleList">
          <el-option
            v-for="item in applyList"
            :key="item.value"
            :label="item.name"
            :value="item.value" />
        </el-select>
        <el-select
          v-model="module"
          style="width: 160px;"
          clearable
          placeholder="操作对象"
          filterable
          :filter-method="(query)=> {filterMethod(query, 'moduleList')}">
          <el-option
            v-for="item in moduleList"
            :key="item.value"
            :label="item.name"
            :value="item.value" />
        </el-select>
        <el-select
          v-model="behavior"
          multiple
          placeholder="操作行为"
          collapse-tags
          filterable
          :filter-method="(query)=> {filterMethod(query, 'behaviorList')}">
          <el-option
            v-for="item in behaviorList"
            :key="item.value"
            :label="item.name"
            :value="item.value" />
        </el-select>
        <el-button
          type="primary"
          @click="refreshList">查询</el-button>
        <el-button
          class="main-table-header-button"
          @click="exportClick">导出</el-button>
      </flexbox>
      <el-table
        v-loading="loading"
        :data="list"
        :class="WKConfig.tableStyle.class"
        :stripe="WKConfig.tableStyle.stripe"
        :height="tableHeight"
        :cell-class-name="cellClassName"
        class="main-table"
        highlight-current-row
        style="width: 100%;"
        @row-click="handleRowClick">
        <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :formatter="tableFormatter"
          show-overflow-tooltip />
      </el-table>
      <div class="p-contianer">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          :total="total"
          class="p-bar"
          background
          layout="prev, pager, next, sizes, total, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 编辑详情 -->
    <edit-detail-dialog
      :visible.sync="editDetailVisible"
      :data="editData" />
  </div>
</template>

<script>
import {
  biLogQueryOperationLogsAPI,
  biLogExportOperateLogAPI,
  biLogQueryApplyAPI,
  biLogQueryBehaviorAPI,
  biLogQueryOperateObjectAPI
} from '@/api/admin/log'

import XrHeader from '@/components/XrHeader'
import WkUserDialogSelect from '@/components/NewCom/WkUserDialogSelect'
import { Loading } from 'element-ui'
import EditDetailDialog from './components/EditDetailDialog'

import { downloadExcelWithResData } from '@/utils'
import { objDeepCopy } from '@/utils'
import PinyinMatch from 'pinyin-match'

export default {
  // 操作日志日志
  name: 'DataHandleLog',
  components: {
    XrHeader,
    WkUserDialogSelect,
    EditDetailDialog
  },
  data() {
    return {
      loading: false, // 加载动画
      tableHeight: document.documentElement.clientHeight - 270, // 表的高度

      fieldList: [
        {
          prop: 'userName',
          label: '操作人',
          width: 100
        },
        {
          prop: 'createTime',
          label: '操作时间',
          width: 180
        },
        {
          prop: 'behaviorName',
          label: '操作行为',
          width: 120
        },
        {
          prop: 'moduleName',
          label: '操作对象',
          width: 100
        },
        {
          prop: 'applyName',
          label: '所属应用',
          width: 80
        },
        {
          prop: 'operationObj',
          label: '操作数据',
          width: 150
        },
        {
          prop: 'clientIp',
          label: 'IP地址',
          width: 140
        },
        {
          prop: 'operationInfo',
          label: '操作详情',
          width: null
        }
      ],

      dateTime: [],
      userList: [],
      apply: '', // 应用详情
      applyList: [], // 应用列表
      applyListCopy: [], // 应用列表
      behavior: [], // 操作行为
      behaviorList: [],
      behaviorListCopy: [],
      module: '', // 操作对象
      moduleList: [],
      moduleListCopy: [],
      list: [],
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 45, 60],
      total: 0,

      postParams: {},
      // 编辑数据查看
      editData: [],
      editDetailVisible: false,
      // 模块详情
      moduleType: '',
      moduleId: '',
      moduleDetailVisible: false
    }
  },
  computed: {
    logData() {
      if (this.$route.name === 'userLog') {
        return {
          label: '用户操作日志',
          labelDes: '主要记录用户对各个模块的增加、编辑、删除等操作的日志。<br>可查询18个月内的日志数据。',
          type: 0, // 0 是普通 1 是设置
          isModule: 1
        }
      }

      return {
        label: '系统设置操作日志',
        labelDes: '可查询18个月内的日志数据。',
        type: 1, // 0 是普通 1 是设置
        isModule: 0
      }
    }
  },
  mounted() {
    const startOfLastWeek = this.$moment().subtract(7, 'days').startOf('day').format('YYYY-MM-DD')
    const today = this.$moment().format('YYYY-MM-DD')
    this.dateTime = [startOfLastWeek, today]

    // 控制table的高度
    window.onresize = () => {
      this.tableHeight = document.documentElement.clientHeight - 270
    }

    this.getList()
    this.getApplyList()
    this.getBehaviorList()
  },
  methods: {
    /**
     * @description: 刷新数据
     * @return {*}
     */
    refreshList() {
      this.currentPage = 1
      this.getList()
    },

    /**
     * @description: 获取操作应用
     * @return {*}
     */
    getApplyList() {
      biLogQueryApplyAPI({ isModule: this.logData.isModule }).then(res => {
        this.applyList = res.data || []
        this.applyListCopy = objDeepCopy(this.applyList)
      }).catch(() => {
      })
    },

    /**
     * @description: 获取操作对象
     * @return {*}
     */
    getModuleList() {
      this.module = ''
      this.moduleList = []
      this.moduleListCopy = []
      biLogQueryOperateObjectAPI({ apply: this.apply }).then(res => {
        this.moduleList = res.data || []
        this.moduleListCopy = objDeepCopy(this.moduleList)
      }).catch(() => {
      })
    },

    /**
     * @description: 获取行为数据
     * @return {*}
     */
    getBehaviorList() {
      this.behaviorList = []
      this.behaviorListCopy = []

      this.behavior = []
      biLogQueryBehaviorAPI().then(res => {
        this.behaviorList = res.data || []
        this.behaviorListCopy = objDeepCopy(this.behaviorList)
      }).catch(() => {

      })
    },

    /**
     * @description: 获取列表数据
     * @return {*}
     */
    getList() {
      this.loading = true
      const params = {
        page: this.currentPage,
        limit: this.pageSize
      }
      if (this.userList && this.userList.length) {
        params.userList = this.userList
      }

      if (this.dateTime && this.dateTime.length) {
        params.startTime = this.dateTime[0]
        params.endTime = this.dateTime[1]
      }

      params.behavior = this.behavior
      params.module = this.module
      params.apply = this.apply

      // 0 是普通 1 是设置
      params.type = this.logData.type

      this.postParams = params
      biLogQueryOperationLogsAPI(params)
        .then(res => {
          const list = res.data.list
          list.forEach(item => {
            try {
              const operationObj = JSON.parse(item.operationObj)
              item.operationObj = operationObj
              item.operationObjType = typeof operationObj === 'object' ? 'object' : 'text'
            } catch (e) {
              item.operationObjType = 'text'
            }

            try {
              const operationInfo = JSON.parse(item.operationInfo)
              item.operationInfo = operationInfo
              item.operationInfoType = typeof operationInfo === 'object' ? 'object' : 'text'
            } catch (e) {
              item.operationInfoType = 'text'
            }
          })
          this.list = list
          this.total = res.data.totalRow
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 当某一行被点击时会触发该事件
     */
    handleRowClick(row, column, event) {
      const value = row[column.property]
      if (column.property == 'operationObj') {
        // 3 不是删除的数据可以点击
        if (row.operationObjType === 'object') {
          if (row.apply == 5) { // 人资
            // 1 候选人
            // 2 招聘职位
            // 3 员工管理
            // 4 薪资档案
            // 5 发放记录
            // 6 KPI考核
            // 7 社保管理
            if (row.module == 1) {
              this.$router.push({ name: 'hrmCandidate', query: {
                event: 'detail',
                id: value.typeId
              }})
            } else if (row.module == 2) {
              this.$router.push({ name: 'hrmPost', query: {
                event: 'detail',
                id: value.typeId
              }})
            } else if (row.module == 3) {
              this.$router.push({ name: 'hrmEmployee', query: {
                event: 'detail',
                id: value.typeId
              }})
            } else if (row.module == 4) {
              this.$router.push({ name: 'hrmSalaryArchives', query: {
                event: 'detail',
                id: value.typeId
              }})
            } else if (row.module == 5) {
              // 方法记录无详情
              // this.$router.push({ name: 'hrmSlipHistory', query: {
              //   event: 'detail',
              //   id: value.typeId
              // }})
            } else if (row.module == 6) {
              this.$router.push({ name: 'KpiAssessment', query: {
                event: 'detail',
                id: value.typeId
              }})
            } else if (row.module == 7) {
              // this.$router.push({ name: 'hrmInsurance', query: {
              //   event: 'detail',
              //   id: value.typeId
              // }})

              this.$router.push({
                name: 'hrmInsuranceDetail',
                params: {
                  id: value.typeId
                }
              })
            }
          } else if (row.apply == 7) { // 系统设置
            if (row.module == 5) { // 员工与部门管理
              this.$router.push({ name: 'employee-dep', query: {
                event: 'detail',
                userId: value.typeId
              }})
            }
          }
        }
      } else if (column.property == 'operationInfo') {
        if (row.operationInfoType === 'object') {
          this.editData = value
          this.editDetailVisible = true
        }
      }
    },

    /**
     * 列表信息格式化
     */
    tableFormatter(row, column) {
      const value = row[column.property]
      if (column.property == 'operationObj') {
        if (row.operationObjType === 'object') {
          return value.typeName
        } else {
          return value
        }
      } else if (column.property == 'operationInfo') {
        if (row.operationInfoType === 'object') {
          return value?.length > 0 ? '编辑详情' : ''
        } else {
          return value
        }
      }
      return value
    },

    /**
     * 通过回调控制class
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      // 3 不是删除的数据可以点击
      if ((column.property === 'operationObj' && row.operationObjType === 'object') ||
        (column.property === 'operationInfo' && row.operationInfoType === 'object')) {
        return 'can-visit'
      } else {
        return ''
      }
    },

    /**
     * @description: 导出
     * @return {*}
     */
    exportClick() {
      const loading = Loading.service({ fullscreen: true, text: '导出中...' })
      biLogExportOperateLogAPI(this.postParams)
        .then(res => {
          downloadExcelWithResData(res)
          loading.close()
        })
        .catch(() => {
          loading.close()
        })
    },

    /**
     * @description: 更改每页展示数量
     * @param {*} val
     * @return {*}
     */
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    /**
     * @description: 更改当前页数
     * @param {*} val 当前页数
     * @return {*}
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    /**
     * @description: 筛选
     * @param {*} query 关键词
     * @param {*} dataKey 数据源 变量名  加Copy为筛选数据源
     * @return {*}
     */
    filterMethod(query, dataKey) {
      if (query !== '') {
        this[dataKey] = this[`${dataKey}Copy`].filter(item => PinyinMatch.match(item.name, query))
      } else {
        this[dataKey] = objDeepCopy(this[`${dataKey}Copy`])
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "./index.scss";

::v-deep .el-select {
  .el-select__tags {
    span {
      .el-tag:first-child {
        max-width: calc(100% - 60px);
      }
    }
  }
}
</style>
